package com.jmye.spring.factory;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Date 2024/12/12 下午11:01
 * @Author jmye
 */
public class BeanFactory {

    private static Map<String, Object> ioc= new HashMap<>();

    static {
        try {
            // 读取配置文件
            InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
            // 解析 XML
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(resourceAsStream);
            // xpath 表达式
            String xpath = "//bean";
            // 获取所有的 bean 标签
            List<Element> nodes = document.selectNodes(xpath);
            for (Element element : nodes) {
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                Object object = Class.forName(className).newInstance();
                ioc.put(id, object);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Object getBean(String id){
        return ioc.get(id);
    }

}
